/*
 * FilePath     : \vite.config.ts
 * Author       : 苏军志
 * Date         : 2023-06-04 08:42
 * LastEditors  : 苏军志
 * LastEditTime : 2025-03-12 18:02
 * Description  : 项目配置文件
 * CodeIterationRecord:
 */
import legacy from "vite-plugin-legacy-swc";
import vue from "@vitejs/plugin-vue";
import vueJsx from "@vitejs/plugin-vue-jsx";
import path from "path";
import AutoImport from "unplugin-auto-import/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import Components from "unplugin-vue-components/vite";
import { defineConfig, loadEnv } from "vite";
import topLevelAwait from "vite-plugin-top-level-await";
import VueDevTools from "vite-plugin-vue-devtools";
import { visualizer } from "rollup-plugin-visualizer";
import progress from "vite-plugin-progress";

export default defineConfig(({ mode }) => {
  const viteEnv = loadEnv(mode, "./");
  return {
    base: viteEnv.VITE_BASE,
    server: {
      port: 6060,
      // 显示IP地址
      host: true,
      // 端口占用直接退出
      strictPort: true,
      // 启动后是否自动打开浏览器
      open: false
    },
    resolve: {
      alias: {
        "@": path.resolve(__dirname, "./src")
      }
    },
    plugins: [
      vue(),
      vueJsx(),
      VueDevTools(),
      topLevelAwait({
        promiseExportName: "__tla",
        promiseImportName: (i: any) => `__tla_${i}`
      }),
      AutoImport({
        dirs: ["src/api/", "src/stores/", "src/utils/", "src/hooks/"],
        // 需要去解析的文件
        include: [
          /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
          /\.vue$/,
          /\.vue\?vue/, // .vue
          /\.md$/ // .md
        ],
        // imports 指定自动引入的包位置（名）
        imports: ["vue", "pinia", "vue-router", "@vueuse/core"],
        // 生成相应的自动导入json文件。
        eslintrc: {
          // 启用
          enabled: true,
          // 生成自动导入json文件位置
          filepath: "./.eslintrc-auto-import.json",
          // 全局属性值
          globalsPropValue: true
        },
        resolvers: [ElementPlusResolver()]
      }),
      Components({
        // imports 指定组件所在目录，默认为 src/components
        dirs: ["src/components/", "src/components/*/", "src/views/*/components/", "src/views/*/*/components/"],
        deep: false,
        // 需要去解析的文件
        include: [/\.vue$/, /\.vue\?vue/, /\.md$/]
      }),
      legacy({
        targets: ["defaults", "ie >= 11", "chrome 49"], //需要兼容的目标列表，可以设置多个
        additionalLegacyPolyfills: ["regenerator-runtime/runtime"],
        renderLegacyChunks: true,
        polyfills: [
          "es.symbol",
          "es.array.filter",
          "es.promise",
          "es.promise.finally",
          "es/map",
          "es/set",
          "es.array.for-each",
          "es.object.define-properties",
          "es.object.define-property",
          "es.object.get-own-property-descriptor",
          "es.object.get-own-property-descriptors",
          "es.object.keys",
          "es.object.to-string",
          "web.dom-collections.for-each",
          "esnext.global-this",
          "esnext.string.match-all"
        ]
      }),
      progress(),
      mode === "analyze" ? visualizer({ open: true }) : undefined
    ],
    build: {
      minify: "terser",
      outDir: "dist",
      assetsDir: "static/assets",
      sourcemap: false,
      // 规定触发警告的 chunk 大小，消除打包大小超过500kb警告
      chunkSizeWarningLimit: 2000,
      // 静态资源打包到dist下的不同目录
      rollupOptions: {
        output: {
          chunkFileNames: "static/js/[name]-[hash].js",
          entryFileNames: "static/js/[name]-[hash].js",
          assetFileNames: "static/[ext]/[name]-[hash].[ext]",
          manualChunks: (id: string) => {
            if (id.includes("node_modules")) {
              for (const key in chunks) {
                if (chunks[key].find((chunk) => id.includes(chunk))) {
                  return key;
                }
              }
              // if (id.includes("node_modules/.store")) {
              //   return id.split("node_modules/.store/")[1].split("/")[0];
              // }
              // return id.split("node_modules/")[1].split("/")[0];
              return undefined;
            }
            // else if (id.includes("src/views/")) {
            //   return id.split("src/views/")[1].split("/")[0];
            // }
            // else if (id.includes("src/")) {
            //   return id.split("src/")[1].split("/")[0];
            // }
          }
        }
      }
    }
  };
});
const chunks: Record<string, string[]> = {
  vue: ["vue", "vue-router", "pinia", "vue-i18n"],
  lodash: ["lodash-es", "lodash-unified"],
  univerCore: ["@univerjs/core", "@univerjs/design"],
  // univerSheets: ["@univerjs/sheets", "@univerjs/sheets-ui", "@univerjs/sheets-formula", "@univerjs/sheets-formula-ui"],
  univerSheetCore: ["@univerjs/sheets", "@univerjs/sheets-ui"],
  // univerDocs: ["@univerjs/docs", "@univerjs/docs-ui"],
  // univerSheetsEngine: ["@univerjs/engine-render", "@univerjs/engine-formula"],
  univerSheetsFormula: ["@univerjs/sheets-formula", "@univerjs/sheets-formula-ui"],
  univerSheetsThread: [
    "@univerjs/sheets-thread-comment",
    "@univerjs/sheets-thread-comment-base"
    // "@univerjs/thread-comment",
    // "@univerjs/thread-comment-ui"
  ],
  univerOther: ["@univerjs/sheets-crosshair-highlight"],
  "zhytech-ui": ["zhytech-ui"]
};
